package com.student.user.controller;

import com.student.common.entity.Result;
import com.student.common.entity.User;
import com.student.user.dto.LoginRequest;
import com.student.user.dto.LoginResponse;
import com.student.user.dto.ChangePasswordRequest;
import com.student.user.service.UserService;
import com.student.user.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 * 
 * @author student
 * @date 2025
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
        try {
            User user = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
            if (user != null) {
                String token = jwtUtil.generateToken(user.getUsername(), user.getRole(), user.getRelatedId());
                LoginResponse response = new LoginResponse(token, user.getUsername(), user.getRealName(), user.getRole(), user.getRelatedId());
                return Result.success(response);
            } else {
                return Result.error("用户名或密码错误");
            }
        } catch (Exception e) {
            return Result.error("登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<String> logout(@RequestParam String username) {
        try {
            userService.logout(username);
            return Result.success("登出成功");
        } catch (Exception e) {
            return Result.error("登出失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo(@RequestParam String username, 
                                   @RequestHeader(value = "Authorization", required = false) String authHeader) {
        try {
            // 从JWT token中获取用户名
            String tokenUsername = null;
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                String token = authHeader.substring(7);
                try {
                    tokenUsername = jwtUtil.getUsernameFromToken(token);
                } catch (Exception e) {
                    return Result.error("Token无效，请重新登录");
                }
            }
            
            // 如果token中没有用户名，则使用请求中的用户名（兼容性处理）
            if (tokenUsername == null) {
                tokenUsername = username;
            }
            
            if (tokenUsername == null || tokenUsername.trim().isEmpty()) {
                return Result.error("无法获取用户信息，请重新登录");
            }
            
            User user = userService.getUserByUsername(tokenUsername);
            if (user != null) {
                return Result.success(user);
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            return Result.error("获取用户信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody User user) {
        try {
            boolean success = userService.register(user);
            if (success) {
                return Result.success("注册成功");
            } else {
                return Result.error("注册失败，用户名已存在");
            }
        } catch (Exception e) {
            return Result.error("注册失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新用户信息
     */
    @PostMapping("/update")
    public Result<String> updateUser(@RequestBody User user) {
        try {
            boolean success = userService.updateUser(user);
            if (success) {
                return Result.success("用户信息更新成功");
            } else {
                return Result.error("用户信息更新失败，用户不存在");
            }
        } catch (Exception e) {
            return Result.error("用户信息更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    public Result<String> changePassword(@RequestBody ChangePasswordRequest request, 
                                       @RequestHeader(value = "Authorization", required = false) String authHeader) {
        try {
            // 从JWT token中获取用户名
            String username = null;
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                String token = authHeader.substring(7);
                try {
                    username = jwtUtil.getUsernameFromToken(token);
                } catch (Exception e) {
                    return Result.error("Token无效，请重新登录");
                }
            }
            
            // 如果token中没有用户名，则使用请求中的用户名（兼容性处理）
            if (username == null) {
                username = request.getUsername();
            }
            
            if (username == null || username.trim().isEmpty()) {
                return Result.error("无法获取用户信息，请重新登录");
            }
            
            boolean success = userService.changePassword(
                username, 
                request.getOldPassword(), 
                request.getNewPassword()
            );
            if (success) {
                return Result.success("密码修改成功");
            } else {
                return Result.error("密码修改失败，当前密码不正确");
            }
        } catch (Exception e) {
            return Result.error("密码修改失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建用户（用于学生/教师创建时同步创建用户）
     */
    @PostMapping("/create")
    public Result<String> createUser(@RequestParam("username") String username,
                                     @RequestParam("realName") String realName,
                                     @RequestParam("role") String role,
                                     @RequestParam("relatedId") String relatedId,
                                     @RequestParam("email") String email,
                                     @RequestParam("phone") String phone) {
        try {
            boolean success = userService.createUser(username, realName, role, relatedId, email, phone);
            if (success) {
                return Result.success("用户创建成功");
            } else {
                return Result.error("用户创建失败，用户名已存在");
            }
        } catch (Exception e) {
            return Result.error("用户创建失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新用户信息（用于学生/教师更新时同步更新用户）
     */
    @PutMapping("/update-info")
    public Result<String> updateUserInfo(@RequestParam("username") String username,
                                        @RequestParam("realName") String realName,
                                        @RequestParam("email") String email,
                                        @RequestParam("phone") String phone) {
        try {
            boolean success = userService.updateUserInfo(username, realName, email, phone);
            if (success) {
                return Result.success("用户信息更新成功");
            } else {
                return Result.error("用户信息更新失败，用户不存在");
            }
        } catch (Exception e) {
            return Result.error("用户信息更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除用户（用于学生/教师删除时同步删除用户）
     */
    @DeleteMapping("/delete")
    public Result<String> deleteUser(@RequestParam("username") String username) {
        try {
            boolean success = userService.deleteUser(username);
            if (success) {
                return Result.success("用户删除成功");
            } else {
                return Result.error("用户删除失败，用户不存在");
            }
        } catch (Exception e) {
            return Result.error("用户删除失败：" + e.getMessage());
        }
    }
    
    // ========== 为Feign客户端提供的简化接口 ==========
    
    /**
     * 创建用户（简化接口，直接返回boolean）
     */
    @PostMapping("/create-simple")
    public boolean createUserSimple(@RequestParam("username") String username,
                                   @RequestParam("realName") String realName,
                                   @RequestParam("role") String role,
                                   @RequestParam("relatedId") String relatedId,
                                   @RequestParam("email") String email,
                                   @RequestParam("phone") String phone) {
        try {
            return userService.createUser(username, realName, role, relatedId, email, phone);
        } catch (Exception e) {
            System.err.println("创建用户失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 更新用户信息（简化接口，直接返回boolean）
     */
    @PutMapping("/update-info-simple")
    public boolean updateUserInfoSimple(@RequestParam("username") String username,
                                       @RequestParam("realName") String realName,
                                       @RequestParam("email") String email,
                                       @RequestParam("phone") String phone) {
        try {
            return userService.updateUserInfo(username, realName, email, phone);
        } catch (Exception e) {
            System.err.println("更新用户信息失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 删除用户（简化接口，直接返回boolean）
     */
    @DeleteMapping("/delete-simple")
    public boolean deleteUserSimple(@RequestParam("username") String username) {
        try {
            return userService.deleteUser(username);
        } catch (Exception e) {
            System.err.println("删除用户失败: " + e.getMessage());
            return false;
        }
    }
}
